package gl.android.biyiqing;

import gl.API;
import gl.App;
import gl.android.biyiqing.adapter.HuBeiQuYuAdapter;
import gl.android.biyiqing.adapter.ShenFenAdapter;
import gl.android.biyiqing.bean.BYQUserInfo;
import gl.android.biyiqing.bean.Result;
import gl.android.biyiqing.event.OnRegiestSuccess;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.func.updoladPicture.SelectPictureActivity;
import gl.func.updoladPicture.TakePicSucess;
import gl.func.updoladPicture.Upload;
import gl.uitls.AndroidUtil;
import gl.uitls.Lg;
import gl.uitls.Tip;
import gl.view.widget.HorizonTextWheel;

import java.io.File;

import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import de.greenrobot.event.EventBus;

public class CompleteUserInfoActivity extends BYQBaseActivity {
	// Content View Elements

	private LinearLayout activity_regist_scroll;
	private LinearLayout content;
	private ImageView regist_photo;
	private View regist_photo_line1;
	private LinearLayout regist_photo_change;
	private TextView regist_complete_avatar_photos;
	private TextView regist_complete_avatar_camera;
	private View regist_photo_line2;
	private TextView regist_email;
	private HorizonTextWheel regist_phone;
	private HorizonTextWheel regist_code;
	private HorizonTextWheel regist_pass;
	private HorizonTextWheel regist_nick;
	private HorizonTextWheel hascar;
	private TextView regist_complete_submit_btn;
	private HorizonTextWheel hasgoufang;
	private String type_avator  = "1-";

	// End Of Content View Elements

	private void bindViews() {

		activity_regist_scroll = (LinearLayout) findViewById(R.id.activity_regist_scroll);
		content = (LinearLayout) findViewById(R.id.content);
		regist_photo = (ImageView) findViewById(R.id.regist_photo);
		regist_photo_line1 = (View) findViewById(R.id.regist_photo_line1);
		regist_photo_change = (LinearLayout) findViewById(R.id.regist_photo_change);
		regist_complete_avatar_photos = (TextView) findViewById(R.id.regist_complete_avatar_photos);
		regist_complete_avatar_camera = (TextView) findViewById(R.id.regist_complete_avatar_camera);
		regist_photo_line2 = (View) findViewById(R.id.regist_photo_line2);
		regist_email = (TextView) findViewById(R.id.regist_email);
		regist_phone = (HorizonTextWheel) findViewById(R.id.regist_phone);
		regist_code = (HorizonTextWheel) findViewById(R.id.regist_code);
		regist_pass = (HorizonTextWheel) findViewById(R.id.regist_pass);
		regist_nick = (HorizonTextWheel) findViewById(R.id.regist_nick);
		hascar = (HorizonTextWheel) findViewById(R.id.hascar);
		hasgoufang = (HorizonTextWheel) findViewById(R.id.hasgoufang);
		regist_complete_submit_btn = (TextView) findViewById(R.id.regist_complete_submit_btn);

		regist_phone.setTextArray(getValue(BYQUserInfo.HUNYINZHUNGKUANG));
		regist_code.setTextArray(getValue(BYQUserInfo.XUELI));
		regist_pass.setTextArray(getValue(BYQUserInfo.ZHIYE));
		regist_nick.setTextArray(getValue(BYQUserInfo.SHOURU));
		hascar.setTextArray(getValue(BYQUserInfo.GOUCHEQINGKUANG));
		hasgoufang.setTextArray(getValue(BYQUserInfo.JUZHUQINGKUANG));

		regist_email.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
//				showShenFenSelectDialog();
				showHuBeiQuYuSelectDialog();

			}
		});
		regist_complete_avatar_photos.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SelectPictureActivity.pickImage(CompleteUserInfoActivity.this, SelectPictureActivity.REQUESTCODE_TAKE_AVATOR,true);
				
			}
		});
		regist_complete_avatar_camera.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SelectPictureActivity.pickImage(CompleteUserInfoActivity.this, SelectPictureActivity.REQUESTCODE_TAKE_AVATOR,true);
			}
		});
		regist_photo.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SelectPictureActivity.pickImage(CompleteUserInfoActivity.this, SelectPictureActivity.REQUESTCODE_TAKE_AVATOR,true);
			}
		});
	}
	class AjaxCallBackForUpload extends AjaxCallBack<String> {
		String temp_type;

		AjaxCallBackForUpload(String type) {
			temp_type = type;
		}

		final String UPLOADFAIL = "上传失败";

		@Override
		public void onSuccess(String t) {
			super.onSuccess(t);
			Lg.i(t);
			try {
				if (!new JSONObject(t).getBoolean("ret")) {
					Tip.show(UPLOADFAIL);
				} else {
					Tip.show("上传成功");
				}

			} catch (Exception e) {
				e.printStackTrace();
				onFailure(e, 0, "");
			}
		}

		@Override
		public void onFailure(Throwable t, int errorNo, String strMsg) {
			super.onFailure(t, errorNo, strMsg);
			Tip.show(UPLOADFAIL);
		}
	};
	public void onEvent(TakePicSucess take) {
		if ( take.getRequestCode() == SelectPictureActivity.REQUESTCODE_TAKE_AVATOR) {
		
			String type = "1-";

			if (take.getRequestCode() == SelectPictureActivity.REQUESTCODE_TAKE_AVATOR) {
				type = type_avator;
				Tip.show("正在上传头像");
				App.mFBitmap.display(regist_photo, "file:///" + take.getPath()[0]);
			} 
			for (String  paths : take.getPath()) {
				Upload.uploadFile(type + UserManger.getInstance().userid + ".jpg",
						new File(paths), new AjaxCallBackForUpload(type));
			}
		}
		
		
	}
	String pID = "0";
	String xID = "0";

	protected void showShenFenSelectDialog() {
		final ExpandableListView listview = new ExpandableListView(this);
		final AlertDialog dialog = AndroidUtil.genCustomViewDialog(this,
				listview).show();
		listview.setAdapter(new ShenFenAdapter(getBaseContext(),
				new ShenFenAdapter.OnSelect() {


					@Override
					public void onselect(String gid, String gname,
							String childid, String cname) {
						dialog.dismiss();
						pID = gid;
						xID = childid;
						regist_email.setText(gname+""+cname);
					}
				}));

	}
	protected void showHuBeiQuYuSelectDialog() {
		final ExpandableListView listview = new ExpandableListView(this);
		final AlertDialog dialog = AndroidUtil.genCustomViewDialog(this,
				listview).show();
		listview.setAdapter(new HuBeiQuYuAdapter(getBaseContext(),
				new ShenFenAdapter.OnSelect() {
			
			
			@Override
			public void onselect(String gid, String gname,
					String childid, String cname) {
				dialog.dismiss();
				pID = gid;
				xID = childid;
				regist_email.setText(gname+""+cname);
			}
		}));
		
	}

	public String[] getValue(final String hUNYINZHUNGKUANG) {

		final String[] readableArray = BYQUserInfo
				.getReadableArray(hUNYINZHUNGKUANG);
		final String[] String = new String[readableArray.length - 1];
		int i = 0;
		for (String s : readableArray) {
			if (i != 0) {
				String[i - 1] = s;
			}
			i++;
		}
		return String;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_complete_userinfo_byq);
		bindViews();
		// if (savedInstanceState == null) {
		// getSupportFragmentManager().beginTransaction()
		// .add(R.id.container, new PlaceholderFragment()).commit();
		// }
		regist_complete_submit_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				setResult();
				complteUserInfo();
			}
		});
	}

	/**
	 * 区域（省）、区域（市）、婚姻、学历、职业、收入、购车情况、购房情况
	 */
	String useroptional = "9,11,1,1,1,1,1,1";

	private void setResult() {
//		useroptional = String.format("%s,%s,%s,%s,%s,%s,%s,%s",
//				getSelectFromTag(regist_email, "省"),
//				getSelectFromTag(regist_email, "区"),
//				getSelect(regist_phone, "年龄"), getSelect(regist_code, "身高"),
//				getSelect(regist_pass, "身高"),
//				getSelect(regist_nick, BYQUserInfo.SHOURU),
//				getSelect(hascar, BYQUserInfo.GOUCHEQINGKUANG),
//				getSelect(hasgoufang, BYQUserInfo.JUZHUQINGKUANG));
		useroptional = String.format("%s,%s,%s,%s,%s,%s,%s",
				/*getSelectFromTag(regist_email, "省"),*/
				getSelectFromTag(regist_email, "区"),
				getSelect(regist_phone, "年龄"), getSelect(regist_code, "学历")+1,
				getSelect(regist_pass, "身高"),
				getSelect(regist_nick, BYQUserInfo.SHOURU)+1,
				getSelect(hascar, BYQUserInfo.GOUCHEQINGKUANG)+1,
				getSelect(hasgoufang, BYQUserInfo.JUZHUQINGKUANG)+1);
		getIntent().putExtra("data", useroptional);
		System.out.println(useroptional);
		setResult(RESULT_OK, getIntent());
	}

	private String getSelectFromTag(TextView regist_email2, String string) {
		if (string.equals("省")) {
			return pID;
		} else {
			return xID;
		}
	}

	private int getSelect(HorizonTextWheel regist_phone2, String string) {

		return regist_phone2.getSelected();
	}

	void complteUserInfo() {

		BaseControl.get(API.URL + "RegUser?userid=%s&data=%s",
				new AjaxCallBack<String>() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						Result userList2 = new Gson().fromJson(t,
								new TypeToken<Result>() {
								}.getType());
						if (!TextUtils.isEmpty(userList2.getMsg())
								&& "2".equals(userList2.getMsg())) {
							Tip.show("资料完善成功！");
							EventBus.getDefault().post(new OnRegiestSuccess());
							finish();
						} else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "0".equals(userList2.getMsg())) {
							Tip.show("资料完善失败 ");
						} else if (!TextUtils.isEmpty(userList2.getMsg())
								&& "1".equals(userList2.getMsg())) {
							Tip.show("数据不正确");
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						Tip.show("" + t.getMessage());
					}
				}, UserManger.getInstance().userid, useroptional);

	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_otheruser_info,
					container, false);
			return rootView;
		}
	}
}
